package com.echo.demo1;

import com.echo.future.ReceiveInvoker;
import com.echo.protocol.MessageProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

public class ClientHandler extends ChannelInboundHandlerAdapter {
    private ExecutorService executorService;

    public ClientHandler(ExecutorService executorService) {
        this.executorService = executorService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        super.channelActive(ctx);
//        ByteBuf buf = Unpooled.copiedBuffer("belkin 安全锁适配器", CharsetUtil.UTF_8);
//        HashMap<String, String> map = new HashMap<>();
//        map.put("123", "123");
//        ctx.channel().writeAndFlush(map);

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        super.channelRead(ctx, msg);
        MessageProtocol messageProtocol = (MessageProtocol) msg;
        executorService.submit(new ReceiveInvoker(messageProtocol));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        ?
        ctx.close();
    }

    public static void main(String[] args) {

        ByteBuf buffer = Unpooled.buffer();

        buffer.writeInt(Integer.MAX_VALUE);
        for (int i = 0; i < 1000; i++) {
            buffer.writeInt(i);
        }
        buffer.writeBytes(new byte[]{97, 115, 100, 102, 105, 100});
        for (int i = 0; i < 100; i++) {
            int i1 = buffer.readInt();
            System.out.println(i1 + "  wIdx:" + buffer.writerIndex()+" ridx:"+buffer.readerIndex() + " cap:"+buffer.capacity());

        }
        System.out.println(buffer);
    }

}
